<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="ru" />
<title>Сравнение структуры баз данных</title>
<body>
<?php

$lev1 = '<div style="display:inline-block;width:32px;"></div>';
$lev2 = '<div style="display:inline-block;width:64px;"></div>';
$lev3 = '<div style="display:inline-block;width:96px;"></div>';

$conf = parse_ini_file( "configs" . DIRECTORY_SEPARATOR . "matvei.conf" );

$parms = array();
$pairs = explode( ';', $conf['dsn'] );
foreach( $pairs as $pair ) {
	$unit = explode('=',$pair);
	$parms[ $unit[0] ] = $unit[1];
}
$dbname = $parms['dbname'];
$sync_file = "data"  . DIRECTORY_SEPARATOR . "pattern.db.struct";

try {
	$db = new PDO( $conf['dsn'], $conf['username'], $conf['password'] );
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$db->exec('SET CHARACTER SET utf8');
	$db->exec("SET time_zone = '".$conf['time_zone_offset']."'");

	$tabnames = array();
	$rs = $db->query("SHOW TABLES FROM ".$dbname);
	while( $row = $rs->fetch(PDO::FETCH_NUM) ) {
		$tabnames[] = $row[0];
	}
	$rs->closeCursor();
	sort( $tabnames );
	
	$tabs = array();
	foreach( $tabnames as $tname ) {
		$tab = new stdClass;
		$tab->name = $tname;
		
		$field = array();
		$rs = $db->query("SHOW COLUMNS FROM ".$tname);
		while( $row = $rs->fetch(PDO::FETCH_NUM) ) {
			$fld = new stdClass;
			$fld->name = $row[0];
			$fld->type = $row[1];
			$fld->isNull = $row[2];
			$fld->key = $row[3];
			$fld->defval = $row[4];
			$fld->extra = $row[5];
			$field[] = $fld;
		}
		$tab->fields = $field;
		$tabs[] = $tab;
		unset( $field );
	}
	
	if( !file_exists( $sync_file ) ) {
		file_put_contents( $sync_file, serialize( $tabs ) );
		echo "Снимок стуктуры базы данных ${dbname} сделан и сохранен в ${sync_file}";
		exit(0);
	}
	
	echo "Проверка наличия таблиц<br>";
	$pat = unserialize( file_get_contents( $sync_file ) );
	for( $i=0; $i<count($pat); $i++ ) {
		$success = false;
		foreach( $tabs as $tab ) {
			if( $pat[$i]->name == $tab->name ) {
				$success = true;
				break;
			}
		}
		if( ! $success ) {
			echo $lev1.$pat[$i]->name." таблица <b>отсутствует</b><br>";
			unset( $pat[$i] );
		}
	}
	
	echo "<br>Проверка соответствия определений полей в таблицах.<br>";
	foreach( $pat as $p ) {
		$ok = "ok";
		echo $lev1.$p->name." проверяем ...";
		foreach( $tabs as $tab ) {
			if( $p->name == $tab->name ) {
				if( count( $p->fields ) != count( $tab->fields ) ) {
					echo "<br>".$lev2."Количество полей <b>не совпадает</b>";
					$ok = '';
				}
				
				foreach( $p->fields as $fp ) {
					$success = false;
					foreach( $tab->fields as $ft ) {
						if( $fp->name == $ft->name ) {
							$success = true;
							if( $fp->type != $ft->type || $fp->isNull != $ft->isNull || $fp->key != $ft->key ||
								$fp->defval != $ft->defval || $fp->extra != $ft->extra ) {
								echo "<br>".$lev2.$fp->name." поле: не соотвествуют '<b>атрибуты или индексы</b>'";
								$ok = '';
							}
							break;
						}
					}
					if( !$success ) {
						echo "<br>".$lev2.$fp->name." поле: <b>отсутствует</b>";
						$ok = '';
					}
				}
				
				break;
			}
		}
		echo $ok."<br>";
	}
}
catch (PDOException $e) {
	echo "<br>Ошибка базы данных: ".$e->getMessage();
}
catch ( Exception $e ) {
	echo "<br>Ошибка: ".$e->getMessage();
}
echo "</body>";
?>